package com.sunmouse.toollib.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;


public abstract class BasicRecyclerAdapter<B, V extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<V> implements View.OnClickListener,View.OnLongClickListener {
    protected List<B> list;
    protected LayoutInflater inflater;
    protected OnChildClickListener mOnChildClickListener;
    protected OnItemClickListener mOnItemClickListener;
    protected OnItemLongClickListener mItemLongClick;


    public BasicRecyclerAdapter(List<B> list, Context context) {
        this.list = list;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public V onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = bindConvertView(inflater, parent, viewType);
        return bindHolder(v);
    }

    @Override
    public void onBindViewHolder(V holder, int position) {
        bindData(list, holder, position);
    }

    protected abstract View bindConvertView(LayoutInflater inflater, ViewGroup parent, int viewType);

    protected abstract V bindHolder(View v);

    protected abstract void bindData(List<B> list, V holder, int position);

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public void onClick(View v) {
//        if (mOnChildClickListener != null && v.getTag() != null) {
//            mOnChildClickListener.onClick(v, (Integer) v.getTag());
//        }
        if (mOnItemClickListener != null && v.getTag() != null) {
            mOnItemClickListener.onItemClick((Integer) v.getTag());
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (mItemLongClick!=null){
            mItemLongClick.onItemLongClick((Integer) v.getTag());
            return true;
        }
        return false;
    }

    /**
     * set on child click listener
     */
    public void setOnChildClickListener(OnChildClickListener listener) {
        this.mOnChildClickListener = listener;
    }

    /**
     * set on Item click
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    /**
     *  on item long click listener
     * @param listener
     */
    public void setOnItemLongClickListener(OnItemLongClickListener listener) {
        this.mItemLongClick = listener;
    }

    /**
     * Created by Kvin on 2017/2/21.
     */
    public interface OnItemClickListener {
        /**
         * use for setting click event for children views
         *
         * @param position
         */
        void onItemClick(int position);
    }

    /**
    *
    *@author leiyun
    *@time 2018/8/2 10:47
    **/
    public interface OnItemLongClickListener {
        void onItemLongClick(int position);
    }
}
